﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Geoinfor.Data;
using maintain_test.Geoinfor.CG.Beckett;

namespace maintain_test
{
    public partial class PersonAdd : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack==true )
            {
                
            }
            else
            {
                Announce announce=new Announce();
                DropCityInit();

                DataTable myDt;
                myDt = new DataTable();
                myDt = CreateDataTable();
                Session["myDatatable"] = myDt;
                this.DataList1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView;
                this.DataList1.DataBind();
            }

        }

        public string DataList1Init()
        {
            StringBuilder stringBuilder = new StringBuilder();
            return stringBuilder.ToString();
        }

        private void DropCityInit()
        {
            DAC dac = new DAC();
            DataSet dsM;

            //--鄉鎮市
            dsM = dac.QueryDataSet("select * from Map_Town_U");
            DrpCity.DataSource = dsM;
            DrpCity.DataTextField = "TOWNNAME";
            DrpCity.DataValueField = "TOWNNAME";
            DrpCity.DataBind();
            DrpCity.Items.Insert(0, new ListItem("請選擇", ""));	//"請選擇部門"
            dsM.Clear();
            DrpCity.Dispose();
        }

        protected void btnUpdata_Click(object sender, EventArgs e)
        {
            FileUpload myFL = new FileUpload();
            myFL = (FileUpload)Page.FindControl("FindFile");
            if (myFL.HasFile)
            {
                if (IsExt(myFL))
                {
                    string filepath = CreateTempDirOn(myFL);
                    AddDataToTable(filepath, (DataTable)Session["myDatatable"]);
                    this.DataList1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView;
                    this.DataList1.DataBind();                    
                    
                }
            }
        }

        private void AddDataToTable(string filepath, DataTable dataTable)
        {
            DataRow row;
            row = dataTable.NewRow();

            row["I"] = Guid.NewGuid().ToString();
            row["filepath"] = filepath;
            dataTable.Rows.Add(row);
        }

        private string CreateTempDirOn(FileUpload myFl)
        {
// ReSharper disable PossibleNullReferenceException
            string fileEstenslon = System.IO.Path.GetExtension(myFl.FileName).ToLower();
// ReSharper restore PossibleNullReferenceException
            Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory + @"Uploads\Maintain\Temp\");
            string randName = string.Format("{0:0000000000}", (new Random()).Next(1000000000)) + fileEstenslon;
            string allpath = System.AppDomain.CurrentDomain.BaseDirectory + @"Uploads\Maintain\Temp\" + randName;

            while (System.IO.File.Exists(allpath))
            {
                randName = string.Format("{0:0000000000}", (new Random()).Next(1000000000)) + fileEstenslon;
                allpath = System.AppDomain.CurrentDomain.BaseDirectory + @"Uploads\Maintain\Temp\" + randName;
            }
            myFl.SaveAs(allpath);
            return @"../Uploads/Maintain/Temp/" + randName; ;
        }

        private bool IsExt(FileUpload myFl)
        {
            bool fileok = false;
// ReSharper disable PossibleNullReferenceException
            string fileEstenslon = System.IO.Path.GetExtension(myFl.FileName).ToLower();
// ReSharper restore PossibleNullReferenceException
            string htmlFileName = myFl.FileName;
            string[] allowEstenslon = new string[] { ".jpg", ".gif" };
            for (int i = 0; i < allowEstenslon.Length; i++)
            {
                if (fileEstenslon == allowEstenslon[i])
                {
                    fileok = true;
                }
            }
            return fileok;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            bool ok = CheckID();
            if (ok)
            {
                AddAnnounce();
            }
        }

        private void AddAnnounce()
        {
            Announce announce = new Announce(Kind.Person,
                                             CDateFormat.NowToDBDate(), 
                                             txtPlace.Text.Trim(), 
                                             txtNextPlace.Text.Trim(), 
                                             txtName.Text.Trim(), 
                                             txtMail.Text.Trim(), 
                                             txtTel.Text.Trim(), 
                                             txtNote.Text.Trim(), 
                                             Status.On, 
                                             "", 
                                             "", 
                                             "", 
                                             DrpCity.SelectedValue, 
                                             RadioRoadClass.SelectedValue, 
                                             "");


            if (announce.Insert()>0)
            {
                string a = "ok";
            }
        }

        private bool CheckID()
        {
            StringBuilder msg = new StringBuilder();
            int i = 0;
            msg.Length = 0;
            if (DrpCity.SelectedValue == "")
            {
                ++i;
                msg.Append("請選擇鄉鎮市\\n");
            }
            if (RadioRoadClass.SelectedValue == "")
            {
                ++i;
                msg.Append("請選擇通報類別\\n");
            }
            if (txtName.Text.Trim() == "")
            {
                ++i;
                msg.Append("請輸入您的大名\\n");
            }
            if (txtPlace.Text.Trim() == "")
            {
                ++i;
                msg.Append("請輸入損壞地點\\n");
            }
            if (txtNote.Text.Trim() == "")
            {
                ++i;
                msg.Append("請輸入狀況描述\\n");
            }
            if (txtMail.Text.Trim() == "")
            {
                ++i;
                msg.Append("請輸入電子信箱\\n");
            }

            if (i == 0)
            {
                return true;
            }
            else
            {

                return false;
            }
        }

        private DataTable CreateDataTable()
        {
            DataTable myDataTable = new DataTable();
            DataColumn[] keys = new DataColumn[1];
            DataColumn myDataColumn;

            myDataColumn = new DataColumn();
            myDataColumn.DataType = Type.GetType("System.String");
            myDataColumn.ColumnName = "I";
            myDataTable.Columns.Add(myDataColumn);
            keys[0] = myDataColumn;

            myDataColumn = new DataColumn();
            myDataColumn.DataType = Type.GetType("System.String");
            myDataColumn.ColumnName = "filepath";
            myDataTable.Columns.Add(myDataColumn);

            myDataTable.PrimaryKey = keys;

            return myDataTable;
        }

        protected void litExample_DataBinding(object sender, System.EventArgs e)
        {
            Literal lit = (Literal)(sender);
            string filePath = Eval("filepath").ToString();

            lit.Text = "<a href=\"" + filePath +
                       "\" title=\"" + "" + "\" class=\"thickbox\" rel=\"gallery-plants1\"><img src=\"" +
                       filePath + "\" alt=\"" + "" + "\"  width=" + 70 + " height=" + 70 + " /></a>";
        }

        protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
        {
            DataList dataList = (DataList)source;

            switch (e.CommandName)
            {
                case "Del":
                    RemoveDataToTable(e.CommandArgument.ToString(), (DataTable)Session["myDatatable"]);
                    this.DataList1.DataSource = ((DataTable)Session["myDatatable"]).DefaultView;
                    this.DataList1.DataBind();
                    break;
            }
        }

        private void RemoveDataToTable(string toString, DataTable dataTable)
        {
            string stri = "I='" + toString + "'";
            DataRow row = dataTable.Select(stri)[0];
            dataTable.Rows.Remove(row);
        }
    }
}
